<template>
  <div>
    <el-card>
      <el-table :data="messageList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="消息内容" />
        <el-table-column prop="isRead" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.isRead === 1 ? 'success' : 'warning'">
              {{ row.isRead === 1 ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="handleMarkRead(row)"
              v-if="row.isRead === 0"
            >
              标记已读
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  listMessage, 
  updateMessage, 
  delMessage 
} from '@/api/message'

const messageList = ref([])

// 获取消息列表
const getMessageList = async () => {
  try {
    const response = await listMessage()
    if (response) {
      messageList.value = response
    } else {
      ElMessage.error('获取消息列表失败: 数据格式异常')
    }
  } catch (error) {
    ElMessage.error(`获取消息列表失败: ${error.message}`)
  }
}

// 标记已读
const handleMarkRead = async (row) => {
  try {
    await updateMessage({
      ...row,
      isRead: 1
    })
    ElMessage.success('已标记为已读')
    getMessageList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除消息
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该消息?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delMessage(row.id)
    ElMessage.success('删除成功')
    getMessageList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

onMounted(() => {
  getMessageList()
})
</script>